﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace TM.QWeibo.Client.UserControls
{
    public partial class MentionUser : UserControl
    {
        private List<SDK.Objects.UserInfo> _allIdolInfos;

        public MentionUser()
        {
            InitializeComponent();
            UserListBox.ItemsSource  = Helper.MentionUserHelper.GetRecent(10);
            _allIdolInfos = Dal.Friends.Instance.GetDownloadedIdolList();
        }

        /// <summary>
        /// 屏幕尺寸
        /// </summary>
        private Size renderSize {
            get {
                return App.Current.RootVisual.RenderSize;
            }
        }

        public Action<SDK.Objects.UserInfo> Selected { get; set; }


        /// <summary>
        /// 切换显示
        /// </summary>
        public void ToggleShow()
        {
            Dispatcher.BeginInvoke(() =>
            {
                UserListGrid.Width = renderSize.Width;
                UserListGrid.Height = renderSize.Height;
                txtKeyword.Text = "";
                popUserList.IsOpen = !popUserList.IsOpen;
                popUserList.UpdateLayout();
                PopupEffect(popUserList.IsOpen);
            });
        }

        /// <summary>
        /// 显示
        /// </summary>
        public void Show()
        {
            Dispatcher.BeginInvoke(() =>
            {
                UserListGrid.Width = renderSize.Width;
                UserListGrid.Height = renderSize.Height;
                txtKeyword.Text = "";
                popUserList.IsOpen = true;
                PopupEffect(popUserList.IsOpen);
                popUserList.UpdateLayout();
                if (_allIdolInfos==null || _allIdolInfos.Count < 1)
                {
                    var rs=MessageBox.Show("下载收听资料到本机可以获得更好的搜索体验，是否现在下载？", "温馨提示", MessageBoxButton.OKCancel);
                    if(rs==MessageBoxResult.OK)
                    {
                        Dal.Friends.Instance.DownloadIdolList(null,
                        () => Dispatcher.BeginInvoke(() =>
                        {
                            _allIdolInfos = Dal.Friends.Instance.GetDownloadedIdolList();
                            (new Helper.MessageBoxHelper()).Show("收听资料下载完成！", "", this.UserListGrid);
                        }));
                    }
                }
            });
        }


        /// <summary>
        /// 隐藏
        /// </summary>
        public void Hide()
        {
            Dispatcher.BeginInvoke(() =>
            {
                popUserList.IsOpen = false;
                txtKeyword.Text = "";
                popUserList.UpdateLayout();
                PopupEffect(popUserList.IsOpen);
            });
        }


        private void PopupEffect(bool isOpen)
        {
            if (isOpen)
            {
                PopupOnStoryboard.Begin();
            }
            else
            {
                PopupOffStoryboard.Begin();
            }
        }


        private void UserListBox_Tap(object sender, GestureEventArgs e)
        {
            if (Selected != null)
            {
                var val = (SDK.Objects.UserInfo)UserListBox.SelectedValue;
                Helper.MentionUserHelper.SetOne(val);
                Selected(val);
            }  
        }

        private bool isLoading { get; set; }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (isLoading) {
                return;
            }
            var keyword = txtKeyword.Text;
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                isLoading = true;
                btnSearch.Content = "...";
                processbar.IsIndeterminate = true;
                Dal.User.Instance.Search(keyword, 1, (rs) =>
                {
                    //我收听的用户靠前显示
                    rs = rs.OrderByDescending(u => u.IsIdolFlag).Take(10).ToList();
                    Dispatcher.BeginInvoke(() =>
                    {
                        isLoading = false;
                        btnSearch.Content = "查找";
                        processbar.IsIndeterminate = false;
                        UserListBox.ItemsSource = rs;
                        btnSearch.Focus();
                    });
                });
            }
            else {
                (new Helper.MessageBoxHelper()).Show("输入关键词进行查询", "出错了", this.UserListGrid);
            }
        }

        private void txtKeyword_GotFocus(object sender, RoutedEventArgs e)
        {
            txtKeyword.Background = new SolidColorBrush(Color.FromArgb(255, 239, 235, 239));
            txtKeyword.BorderThickness = new Thickness(1);
            txtKeyword.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 148, 150, 148)); 
        }

        private void txtKeyword_LostFocus(object sender, RoutedEventArgs e)
        {
            txtKeyword.Background = new SolidColorBrush(Color.FromArgb(255, 239, 239, 239));
            txtKeyword.BorderThickness = new Thickness(1);
            txtKeyword.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 148, 150, 148)); 
        }

        private void txtKeyword_KeyUp(object sender, KeyEventArgs e)
        {
            var k = txtKeyword.Text.Trim();
            if (string.IsNullOrWhiteSpace(k))
            {
                return;
            }
            if (e.Key == Key.Enter)
            {
                this.Focus();
                btnSearch_Click(null, new RoutedEventArgs());
            }
            //else
            //{
            //    if (_allIdolInfos == null || _allIdolInfos.Count < 1)
            //    {
            //        return;
            //    }
            //    var rs = new List<SDK.Objects.UserInfo>();
            //    _allIdolInfos.ForEach(o=>
            //                     {
            //                         if (rs.Count < 10 && (o.Name.IndexOf(k, System.StringComparison.CurrentCultureIgnoreCase) > -1 || o.NickName.IndexOf(k, System.StringComparison.CurrentCultureIgnoreCase) > -1))
            //                         {
            //                             rs.Add(o);
            //                         }
            //                     });
            //    UserListBox.ItemsSource = rs;
            //}
        }

        private void txtKeyword_TextChanged(object sender, TextChangedEventArgs e)
        {
            var k = txtKeyword.Text.Trim();
            if (string.IsNullOrWhiteSpace(k))
            {
                return;
            }
            if (_allIdolInfos == null || _allIdolInfos.Count < 1)
            {
                return;
            }
            var rs = new List<SDK.Objects.UserInfo>();
            _allIdolInfos.ForEach(o =>
            {
                if (rs.Count < 10 && (o.Name.IndexOf(k, System.StringComparison.CurrentCultureIgnoreCase) > -1 || o.NickName.IndexOf(k, System.StringComparison.CurrentCultureIgnoreCase) > -1))
                {
                    rs.Add(o);
                }
            });
            UserListBox.ItemsSource = rs;
        }

    }
}
